package cn.itcast.bos.service.impl;

import java.util.List;
import java.util.Set;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.bos.domain.base.Courier;
import cn.itcast.bos.repository.CourierRepository;
import cn.itcast.bos.service.CourierService;

@Service
@Transactional
public class CourierServiceImpl implements CourierService {

	@Autowired
	private CourierRepository courierRepository;

	@Override
	public void save(Courier courier) {

		courierRepository.save(courier);
	}

	@Override
	public Page<Courier> findPageDate(PageRequest pages) {

		return courierRepository.findAll(pages);
	}

	@Override
	public Page<Courier> findPageQueryByCondition(Specification<Courier> specification, PageRequest pageable) {

		return courierRepository.findAll(specification, pageable);
	}

	@Override
	public void deleteCourier(String ids) {
		String[] list = ids.split(",");
		for (int i = 0; i < list.length; i++) {
			Integer id = Integer.parseInt(list[i]);
			courierRepository.updateDelTag(id);
		}

	}

	@Override
	public void recoverCourier(String ids) {
		String[] list = ids.split(",");
		for (int i = 0; i < list.length; i++) {
			Integer id = Integer.parseInt(list[i]);
			courierRepository.recoverDelTag(id);
		}

	}

	// 查询没有被关联定区的快递员
	public List<Courier> findNoAssociation() {
		// 封装Specification，查询没有被关联定区的快递员，即fixedAreas的集合字段为null
		Specification<Courier> specification = new Specification<Courier>() {
			// 查询条件，判定列表size为空
			@Override
			public Predicate toPredicate(Root<Courier> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				Predicate p = cb.isEmpty(root.get("fixedAreas").as(Set.class));
				return p;
			}
		};
		return courierRepository.findAll(specification);

	}

	@Override
	public List<Courier> findAssociationCourier(String fixedAreaId) {
		// TODO Auto-generated method stub
		return courierRepository.findAssociationCourier(fixedAreaId);
	}
}
